<template>
  <div class="top-panel">
    <div class="top-panel-left">
      <!-- 主题 -->
      <div class="dropdown-icon theme">
        <o-tool-button
          type="dropdown"
          @on-click="updateTheme"
          icon="wy-icon wy-apps"
        >
          <div slot="drop">
            <div class="themeBox">
              <div
                class="themeSys"
                v-for="(themes, key) in themeConfig"
                :key="key"
              >
                <span class="dropdown-title">{{
                  $srv.getI18nByPath(`menu.theme.${key}`)
                }}</span>
                <DropdownItem
                  v-for="(item, idx) of themeConfig[key]"
                  :key="idx"
                  :name="item.title"
                  ><img
                    v-if="item.image !== undefined"
                    class="theme-image"
                    :src="item.image"
                  />
                  <i
                    v-if="item.preview !== ''"
                    :style="{ 'background-color': item.preview }"
                    :class="[
                      'theme-image',
                      { 'wy-audit': currentThemeId === item.id },
                      { 'theme-selected': currentThemeId === item.id }
                    ]"
                  ></i>
                  <span class="theme-text">{{
                    $srv.getI18nBySrv(item.title)
                  }}</span>
                  <span
                    v-show="
                      key === 'sysThemes'
                        ? isAdministratorRole
                          ? true
                          : false
                        : true
                    "
                  >
                    <i
                      class="theme-insert wy-icon wy-icon-test"
                      @click.stop="themeDataChange(item, 'insert')"
                    >
                    </i>
                    <i
                      class="theme-edit wy-icon wy-xies"
                      @click.stop="themeDataChange(item, 'edit')"
                    ></i>
                    <i
                      class="theme-delete wy-icon wy-huishouzhan1"
                      @click.stop="themeDataChange(item, 'delete')"
                    ></i>
                    <span class="theme-cover"></span
                  ></span>
                </DropdownItem>
                <div
                  @click="themeDataChange({}, 'insert')"
                  v-show="themeConfig[key].length === 0"
                  class="temp-add wy-icon wy-icon-test"
                ></div>
              </div>
            </div>
          </div>
        </o-tool-button>
      </div>
      <!-- 历史 -->
      <div class="dropdown-icon history">
        <o-tool-button
          type="dropdown"
          @on-click="selectFunc"
          icon="wy-icon wy-clock"
        >
          <div slot="drop">
            <span class="dropdown-title">{{
              $srv.getI18nByPath('menu.openHistory')
            }}</span>
            <DropdownItem
              v-for="(item, idx) of historyConfig.historyOpen"
              :key="idx"
              :name="item.value"
            >
              {{ item.text }}
            </DropdownItem>
          </div>
        </o-tool-button>
      </div>
    </div>
    <div class="top-panel-right">
      <!-- 搜索 -->
      <div class="search-main">
        <AutoComplete
          v-model="searchConfig.value"
          @on-change="handleMainSearchChange"
          @on-search="handleMainSearch"
          @on-select="handleMainSearchSelect"
          icon="ios-search"
          :placeholder="$srv.getI18nByPath(searchConfig.placeholder)"
          size="small"
          :clearable="true"
        >
          <div
            class="search-result-item"
            v-for="(item, key) in searchConfig.result"
            :key="key"
          >
            <div class="search-result-group">
              <span>{{ $srv.getI18nBySrv(key) }}</span>
            </div>
            <Option
              v-for="(option, idx) in item"
              :value="option.funID + ' ' + option.title"
              :key="idx"
            >
              <span class="search-result-title">{{
                $srv.getI18nBySrv(option.title)
              }}</span>
            </Option>
          </div>
        </AutoComplete>
      </div>
      <!-- 待办/消息/通知 -->
      <div
        v-for="(section, key) of sysMsgTips"
        :class="['dropdown-icon']"
        :key="key"
        v-show="key !== 'count'"
      >
        <!-- :icon="'wy-icon wy-' + section.config.iconName" -->
        <o-tool-button
          type="dropdown"
          @on-click="selectFunc"
          :title="$srv.getI18nByPath(`menu.${section.config.title}.title`)"
          :icon="'wy-icon wy-list'"
          :dot="section.config.count.unread !== 0"
        >
          <div slot="drop">
            <!-- $srv.getI18nByPath('menu.' + section.config.title + '.' + item.title) -->
            <DropdownItem
              v-for="(item, idx) of section.el"
              :key="idx"
              :name="section.config.title + '|' + item.title"
              >{{ $srv.getI18nBySrv(item.title)
              }}<span v-show="item.count.unread !== 0" class="dropdown-dot">{{
                item.count.unread
              }}</span></DropdownItem
            >
          </div>
        </o-tool-button>
      </div>
      <!-- 错误/帮助 -->
      <div
        v-for="(section, idx) of funcConfig"
        :class="['dropdown-icon']"
        :key="idx"
      >
        <o-tool-button
          type="dropdown"
          @on-click="selectFunc"
          :title="$srv.getI18nByPath(section.config.title)"
          :icon="section.config.iconName"
          :dot="section.config.dot !== 0"
        >
          <div slot="drop">
            <!-- <span class="dropdown-title">{{
              $srv.getI18nByPath(section.config.title)
            }}</span> -->
            <DropdownItem
              v-for="(item, idx2) of section.el"
              :key="idx2"
              :name="$srv.getI18nByPath(item.value)"
              >{{ $srv.getI18nByPath(item.label)
              }}<span v-show="item.dot !== 0" class="dropdown-dot">{{
                item.dot
              }}</span></DropdownItem
            >
          </div>
        </o-tool-button>
      </div>
      <!-- 语言 -->
      <div class="language">
        <o-tool-button
          type="dropdown"
          @on-click="changeLang"
          :title="langSimpfy.current"
        >
          <div slot="drop">
            <DropdownItem
              v-for="(item, idx) of langConfig.options"
              :key="idx"
              :selected="langConfig.current == item.value"
              :name="item.value"
              >{{ item.label }}</DropdownItem
            >
          </div>
        </o-tool-button>
      </div>
      <!-- 用户 -->
      <div class="user">
        <Dropdown @on-click="userFuncClicked">
          <div class="user_cover">
            <span class="user_name">{{ $store.getters.UserName }}</span>
            <div class="user_icon"><Icon type="md-person" /></div>
          </div>
          <DropdownMenu slot="list">
            <DropdownItem name="logout">{{
              $srv.getI18nByPath('menu.user.cancellation')
            }}</DropdownItem>
            <DropdownItem name="chgPwd">{{
              $srv.getI18nByPath('menu.user.changepassword')
            }}</DropdownItem>
          </DropdownMenu>
        </Dropdown>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { Watch } from 'vue-property-decorator';
import { N_home, T_srv, Tsrv, ifs, ts, vue } from './config';

@T_srv.comp({
  name: 'rightTopMenu'
})
export default class rightTopMenu extends vue {
  [x: string]: any;

  @T_srv.getter('SysMsgTips') sysMsgTips;

  @T_srv.prop({ required: true })
  historyConfig: N_home.HistoryConfig;

  @T_srv.prop({ required: true })
  navConfig: Array<N_home.navRootEle>;

  @T_srv.prop({ required: true })
  funcConfig: any;

  // 父组件compBoxInfo
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  @Watch('funcConfig', { deep: true })
  funcConfigChange(val: any) {
    this.$forceUpdate();
  }

  private GT_compBoxInfo: ifs.I_compBoxInfo;

  private GT_compBox: ifs.I_compBox;

  private G_compID: string;

  private langConfig = {
    current: '',
    options: [
      {
        value: 'zh-CN',
        label: '简体中文'
      },
      {
        value: 'en-US',
        label: 'English'
      },
      {
        value: 'zh-TW',
        label: '繁体中文'
      }
    ]
  };

  private searchConfig = {
    value: '',
    placeholder: 'menu.functionSearch',
    result: {}
  };

  private themeConfig: N_home.themeConfig = {
    sysThemes: [
      {
        id: '',
        title: '',
        f_type: 0,
        f_comment: '',
        preview: ''
      }
    ],
    userThemes: [
      {
        id: '',
        title: '',
        f_type: 1,
        f_comment: '',
        preview: ''
      }
    ]
  };

  // 当前语言简化
  private langSimpfy: N_home.LangSimpfy = {
    current: '',
    options: {
      'zh-CN': '简体',
      'en-US': 'EN',
      'zh-TW': '繁体'
    }
  };

  private currentThemeId: string = '';

  // 是否为管理员角色
  private isAdministratorRole: boolean =
    Tsrv.store.getters.SysInfo.roleInfo[0].roleType === 1;

  private btnStatus: string = '';

  created() {
    this.G_compID = Tsrv.utils.getGUID();
    // 如果外部有传入组件信息
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox = new ts.T_compBox(this.G_compID); // 使用本地实例
    } else {
      this.G_compID = this.compBoxInfo.compID;
      this.GT_compBox = this.compBoxInfo.TcompBox;
    }
    this.GT_compBoxInfo = { compID: this.G_compID, TcompBox: this.GT_compBox };

    this.$languageSetter.initLanguage().then((lang: string) => {
      this.langConfig.current = lang;
      this.langSimpfy.current = this.langSimpfy.options[lang];
    });
  }

  mounted() {
    this.GT_compBox.addCompMergeName(this.G_compID, 'rightTopMenu', this);
    this.$emit('compBoxInfo', this.GT_compBoxInfo);

    // 获取主题
    setTimeout(() => {
      this.getThemes();
    }, 300);
  }

  destroyed() {
    // 如果父组件传入的compBoxInfo则删除本文件产生的引用，反之是本组件产生的ID统一删除
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, ['rightTopMenu']);
    }
  }

  // 更新主题
  private updateTheme(val: any) {
    let PPid;
    for (const key in this.themeConfig) {
      for (const iterator of this.themeConfig[key]) {
        if (iterator.title === val) {
          PPid = iterator.id;
          break;
        }
      }
    }
    if (Tsrv.noValue(PPid)) return;
    Tsrv.TPP.template(PPid)
      .then(res => {
        if (res) {
          this.currentThemeId = Tsrv.TPP.getCurrentUITempID();
        }
      })
      .catch(err => {
        this.$msg(err);
      });
  }

  private selectFunc(val: any) {
    this.$emit('selectFunc', val);
  }

  private handleMainSearchChange(value: string) {
    value === '' && (this.searchConfig.result = {});
  }

  private handleMainSearchSelect(value: string) {
    const arr: string[] = value.split(' ');
    this.$emit('addTab', arr[1]);
    this.searchConfig.value = '';
    this.$nextTick(() => {
      this.searchConfig.result = {};
    });
  }

  private handleMainSearch(value: string) {
    value = value.toLowerCase();
    const navlist: Array<N_home.navRootEle> = Tsrv.utils.clone(
      this.navConfig,
      true
    );
    const result: any = {};
    navlist.forEach((rootnav: any) => {
      rootnav.menus.forEach((group: any) => {
        const find = Tsrv.utils.filter(
          group.groupMembers,
          el =>
            el.title.toLowerCase().indexOf(value) > -1 ||
            Tsrv.getI18nBySrv(el.title)
              .toLowerCase()
              .indexOf(value) > -1
        );
        if (find && find.length > 0) {
          if (!result[rootnav.title]) result[rootnav.title] = [];
          result[rootnav.title] = result[rootnav.title].concat(find);
        }
      });
    });
    this.searchConfig.result = result;
  }

  // 更改语言
  public changeLang(val: string) {
    const chan = this.langConfig.options;
    for (const i in chan) {
      if (chan[i].value === val) {
        if (this.langConfig.current !== val) {
          this.$languageSetter.setLanguage(val);
          this.langConfig.current = val;
        }
        this.langSimpfy.current = this.langSimpfy.options[val];
      }
    }
  }

  // 用户选项
  public userFuncClicked(name: string) {
    switch (name) {
      case 'logout':
        this.logout();
        break;
      case 'chgPwd':
        this.chgPwd();
        break;
      default:
        throw new Error(`err`);
    }
  }

  // 登出
  public logout() {
    this.$Modal.confirm({
      // title: "注销",
      // content: "是否要注销？",
      // okText: "是",
      // cancelText: "取消",
      title: Tsrv.getI18nByPath('menu.cancellation') as string,
      content: Tsrv.getI18nByPath('menu.wantcancellation') as string,
      okText: Tsrv.getI18nByPath('others.ok') as string,
      cancelText: Tsrv.getI18nByPath('others.cancel') as string,
      onOk: () => {
        this.$store.dispatch('LogOut').then((res: any) => {
          Tsrv.cookies.logOut();
          this.$router.push({ path: Tsrv.lexicon.routerPath.login.path });
        });
      },
      onCancel: () => {}
    });
  }

  // 更改密码
  public chgPwd() {
    this.selectFunc('user|chgpwd');
  }

  private getThemes() {
    this.themeConfig = {
      sysThemes: [],
      userThemes: []
    };
    const sysThemes = Tsrv.TPP.getDefConfig();
    const userThemes = Tsrv.TPP.getPersonalConfig();
    sysThemes.forEach(item => {
      const obj = {
        id: item.id,
        title: item.title,
        f_type: item.f_type,
        f_comment: item.f_comment,
        preview: item.preview
      };
      this.themeConfig.sysThemes.push(obj);
    });
    userThemes.forEach(item => {
      const obj = {
        id: item.id,
        title: item.title,
        f_type: item.f_type,
        f_comment: item.f_comment,
        preview: item.preview
      };
      this.themeConfig.userThemes.push(obj);
    });
    this.currentThemeId = Tsrv.TPP.getCurrentUITempID();
  }

  private themeDataChange(item: any, val: string) {
    switch (val) {
      case 'insert':
        this.themeInsert(item);
        break;
      case 'edit':
        this.themeEdit(item);
        break;
      case 'delete':
        this.themeDelete(item);
        break;
      default:
        break;
    }
  }

  // 新增模板
  private themeInsert(val: any) {
    Tsrv.utils
      .createModal('o-userpref', val)
      .then(res => {
        if (!Tsrv.utils.noValue(res)) {
          const template = {
            _sys_user_id: res._sys_user_id,
            classification: 0,
            f_data: JSON.stringify(res.f_data),
            f_comment: res.f_comment,
            preview: res.preview,
            f_type: res.f_type,
            title: res.title
          };
          Tsrv.TPP.saveTemplate(template)
            .then(res1 => {
              this.$msg(res1);
              this.getThemes();
            })
            .catch(err => {
              this.$msg(err);
            });
        }
      })
      .catch(err => {
        this.$msg(err);
      });
  }

  // 编辑模板
  private themeEdit(val: any) {
    Tsrv.utils
      .createModal('o-userpref', val)
      .then(res => {
        if (!Tsrv.utils.noValue(res)) {
          const template = {
            id: res.id,
            _sys_user_id: res._sys_user_id,
            classification: 0,
            f_data: JSON.stringify(res.f_data),
            f_comment: res.f_comment,
            preview: res.preview,
            f_type: res.f_type,
            title: res.title
          };
          Tsrv.TPP.saveTemplate(template)
            .then(res1 => {
              this.$msg(res1);
              this.getThemes();
            })
            .catch(err => {
              this.$msg(err);
            });
        }
      })
      .catch(err => {
        this.$msg(err);
      });
  }

  // 删除模板
  private themeDelete(val: any) {
    if (!Tsrv.utils.noValue(val)) {
      Tsrv.TPP.deleteTemplate(val)
        .then(res => {
          this.$msg(res);
          this.getThemes();
        })
        .catch(err => {
          this.$msg(err);
        });
    }
  }
}
</script>
<style scoped lang="scss">
.top-panel {
  position: absolute;
  top: 0;
  left: 0;
  height: 48px;
  width: 100%;
  background-color: var(--top-bg-color);
  border-bottom: 1px solid $default-border-color;
  .top-panel-right {
    position: absolute;
    right: 0;
    top: 0;
    display: flex;
    flex-direction: row;
    height: 48px;
    .user {
      position: relative;
      height: 48px;
      padding: 10px 0;
      margin: 0 11px 0 5px;
      .user_cover {
        position: relative;
        display: flex;
        height: 30px;
        &:hover {
          .user_name {
            color: var(--top-btn-hover-font-color);
            background-color: var(--top-btn-hover-bg-color);
          }
        }
      }
      .user_name {
        line-height: 28px;
        display: block;
        color: var(--top-font-color);
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .user_icon {
        width: 28px;
        height: 28px;
        text-align: center;
        margin: 1px 9px;
        border-radius: 100%;
        background-color: #808695;
        color: #fff;
        line-height: 28px;
        cursor: pointer;
      }
    }
    .user ::v-deep .ivu-icon-md-person {
      font-size: 18px;
      padding: 5px;
      &:hover {
        color: #fff;
      }
    }

    .language {
      position: relative;
      width: 56px;
      height: 48px;
      display: flex;
      align-items: center;
    }
  }
  .top-panel-left {
    position: absolute;
    left: 5px;
    top: 0;
    display: flex;
    flex-direction: row;
    height: 48px;
  }
}

.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

/* 地址和内容 iview UI */
.dropdown-icon {
  display: flex;
  align-items: center;
  margin: 0 4px;
  .dropdown-title {
    padding: 7px 16px;
    display: block;
    font-weight: bold;
    cursor: default;
  }
  .dropdown-dot {
    display: inline-block;
    border-radius: 15px;
    // background-color: #e1e1e1;
    background: #ed4014;
    color: #fff;
    padding: 1px 5px;
    font-size: 10px;
    font-weight: bold;
    text-align: center;
    margin-left: 7px;
  }
}
.msg .ivu-icon {
  font-size: 20px;
}
.notify .ivu-icon {
  font-size: 19px;
}

.search-main ::v-deep {
  height: 30px;
  border-radius: 15px;
  border: 1px solid var(--default-border-color);
  margin: 8px 10px;
  padding: 0 5px;
  position: relative;
  background-color: var(--globalSearch-input-bg-color);
  .ivu-auto-complete {
    .ivu-select-dropdown {
      width: 100%;
      margin-left: -10px;
      left: 10px !important;
    }
    input {
      height: 28px;
      border: none;
      padding: 0 10px 0 32px;
      border-radius: 15px;
      background-color: var(--globalSearch-input-bg-color);
    }
    .ivu-icon {
      height: 28px;
      width: 28px;
      font-size: 16px;
      position: absolute;
      left: 2px;
      line-height: 28px;
    }
    .search-result-item {
      padding: 4px 0;
      border-bottom: 1px solid #ddd;
      .search-result-group {
        font-size: 12px;
        padding: 4px 0;
        span {
          color: #666;
          font-weight: bold;
          padding: 7px 16px;
        }
      }
    }
    .search-result-item:last-child {
      border-bottom: 0;
    }
  }

  .ivu-icon-ios-close {
    cursor: pointer;
  }
}
.history ::v-deep .ivu-select-dropdown {
  left: 0px !important;
  .ivu-dropdown-menu {
    width: 300px;
    padding: 0 10px;
    .ivu-dropdown-item {
      float: left;
      clear: none;
      background-color: #f6f6f6;
      border-radius: 1px;
      margin: 4px 5px;
      transition: var(--animation-hover);
      .dropdown-title {
        padding: 7px 5px;
      }
    }
    .ivu-dropdown-item:hover {
      color: var(--default-hover-font-color);
      background-color: #e8e8e8;
    }
  }
}

%basic-tool {
  position: absolute;
  opacity: 0;
  visibility: hidden;
  background: #fff;
  padding: 5px;
  border-radius: 25px;
  transition: opacity 0.3s, visibility 0.3s, top 0.3s, left 0.3s,
    background 0.3s;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
%basic-tool-hover {
  left: 90%;
  opacity: 1;
  visibility: visible;
  background: #fff;
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  &:hover {
    fill: #fff;
  }
}

.theme ::v-deep .ivu-select-dropdown {
  left: 0px !important;
  .ivu-dropdown-menu {
    width: 388px;
    padding: 0 10px;
    .ivu-dropdown-item {
      float: left;
      clear: none;
      border-radius: 1px;
      margin: 4px 5px;
      position: relative; // 新
      .theme-image {
        display: block;
        height: 48px;
        width: 48px;
        border-radius: 5px;
        overflow: hidden;
        // &:
      }
      .theme-selected {
        font-family: 'wy-icon' !important;
        font-size: 32px;
        font-style: normal;
        -webkit-font-smoothing: antialiased;
        -moz-osx-font-smoothing: grayscale;
        line-height: 1.5;
        text-align: center;
        color: #fff;
      }
      .theme-text {
        display: block;
        text-align: center;
        padding: 4px 0;
      }

      &:hover {
        .theme-insert {
          @extend %basic-tool-hover;
          top: -5%;
          transform: translate(-30%, -3px);
          // top: 20%;
          // left: 90%;
          // transform: translate(-30%, -50%);
          &:hover {
            color: #57a3f3; // #57a3f3
            background: #e9ecf3;
          }
        }

        .theme-edit {
          @extend %basic-tool-hover;
          top: 25%;
          transform: translateY(-3px);
          // top: 50%;
          // left: 90%;
          // transform: translateY(-50%);
          &:hover {
            color: #1db954;
            background: #e9ecf3;
          }
        }

        .theme-delete {
          @extend %basic-tool-hover;
          top: 55%;
          transform: translate(-30%, -3px);
          // top: 80%;
          // left: 90%;
          // transform: translate(-30%, -50%);
          &:hover {
            color: #f17c7c;
            background: #e9ecf3;
          }
        }

        .theme-cover-zone {
          position: absolute;
          top: 10%;
          left: 20%;
          height: 80%;
          visibility: visible;
          z-index: -1;
        }
      }

      .theme-edit {
        @extend %basic-tool;
        font-size: 12px;
        top: 25%;
        left: 50%;
        transform: translate(-50%, -3px);
        fill: #1db954;
      }

      .theme-insert {
        @extend %basic-tool;
        font-size: 12px;
        top: 25%;
        left: 50%;
        transform: translate(-50%, -3px);
        fill: #ea4c89;
      }

      .theme-delete {
        @extend %basic-tool;
        font-size: 12px;
        top: 25%;
        left: 50%;
        transform: translate(-50%, -3px);
        fill: #000;
      }

      .theme-cover-zone {
        position: absolute;
        width: 100%;
        height: 100%;
        top: 0;
        left: 20%;
        opacity: 0;
        visibility: hidden;
        background: #fff;
        z-index: -1;
      }
    }
  }

  .themeBox {
    display: flex;
    flex-direction: column;
    justify-content: center;
    .temp-add {
      height: 80px;
      width: 80px;
      border-radius: 80px;
      background-color: #f6f6f6;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 8px 16px;
      margin: 4px 5px;
      transition: var(--animation-hover);
      font-size: 30px;
      cursor: pointer;
      &:hover {
        background-color: #e8e8e8;
      }
    }
  }
}
.top-panel-func-text {
  display: none;
}

::v-deep .o-toolbutton {
  .disabled {
    // $color: var(--basegrid-toolbar-btn-fontColor);
    // color: rgba($color, 0.1);
    background-color: transparent;
  }
  .titbtn {
    color: var(--top-font-color);
    &:hover:not(.disabled) {
      color: var(--top-btn-hover-font-color) !important;
      background-color: var(--top-btn-hover-bg-color) !important;
    }
  }
}
@media screen and (max-width: 1024px) {
  .search-main > .ivu-auto-complete ::v-deep {
    width: 150px !important;
    .ivu-select-dropdown {
      width: 260px;
    }
  }
}
@media screen and (min-width: 1024px) {
  .top-panel-func-text {
    display: block;
  }
  .search-main > .ivu-auto-complete {
    width: 260px !important;
  }
}
</style>
